import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { commonGetCityList } from '@/api/common'
import { resetRouter } from '@/router'
import md5 from 'js-md5'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = { 
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: username.trim(), password: md5(password).toUpperCase() }).then(async data => {
        // 在登录前，先获取一下城市列表
        data = await commonGetCityList({ geoLevel: 4, provinceId: 11 })
        localStorage.setItem('city', JSON.stringify(data))
        setToken('success')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_AVATAR', 'admin')
      resolve('admin')
      // getInfo({ id: sessionStorage.getItem('user_id') }).then(data => {
      //   if (!data) {
      //     return reject('Verification failed, please Login again.')
      //   }

      //   const { titleName, role, contactPerson, menu, setup, menuExpireTime } = data
      //   let roles = role==0?['admin']:['shoper'];
      //   commit('SET_NAME', titleName)
      //   //设置权限
      //   commit('SET_AVATAR', roles)

      //   sessionStorage.setItem('titleName', titleName)
      //   sessionStorage.setItem('role', role)
      //   sessionStorage.setItem('contactPerson', contactPerson)
      //   sessionStorage.setItem('menu', JSON.stringify(menu))
      //   sessionStorage.setItem('setup', JSON.stringify(setup))
      //   sessionStorage.setItem('menuExpireTime', menuExpireTime)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

